<script>
import { useUserStore } from '../../stores/user'
import DeviceApi from '../../api/device'
import DeviceFeedbackForm from '@/components/deviceFeedback/DeviceFeedbackForm.vue'

export default {
  components: {
    DeviceFeedbackForm
  },
  data() {
    return {
      bookings: [],
      loading: false,
      showForm: false,
      currentBooking: null,
      showCommentDialog: false,
      selectedStatus: 'all',
      returnNote: '用户操作归还'
    }
  },
  computed: {
    userStore() {
      return useUserStore()
    },
    filteredBookings() {
      if (this.selectedStatus === 'all') {
        return this.bookings;
      }
      return this.bookings.filter(booking => {
        if (this.selectedStatus === 'commented') {
          return booking.status === 'completed' && booking.hasComment;
        }
        return booking.status === this.selectedStatus;
      });
    }
  },
  methods: {
    async fetchBookings() {
      this.loading = true
      try {
        const api = new DeviceApi()
        const res = await api.getUserBookings()
        if (res.code === 200) {
          this.bookings = res.data
        } else {
          this.$myMessageBox(res.msg || '获取预约记录失败')
        }
      } catch (err) {
        console.error('Error fetching bookings:', err)
        this.$myMessageBox('获取预约记录失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    async cancelBooking(bookingId) {
      try {
        const api = new DeviceApi()
        const res = await api.cancelBooking(bookingId)
        if (res.code === 200) {
          this.$myMessageBox('预约已取消')
          this.fetchBookings() // 刷新列表
        } else {
          this.$myMessageBox(res.msg || '取消预约失败')
        }
      } catch (err) {
        console.error('Error canceling booking:', err)
        this.$myMessageBox('取消预约失败，请稍后重试')
      }
    },
    async returnDevice(bookingId) {
      try {
        const api = new DeviceApi()
        console.log('Returning device with bookingId:', bookingId)
        const returnNote = '用户操作归还'
        const res = await api.returnDevice({
          bookingId: bookingId,
          returnNote: returnNote
        })
        if (res.code === 200) {
          this.$myMessageBox('设备已归还')
          this.fetchBookings() // 刷新列表
        } else {
          this.$myMessageBox(res.msg || '归还设备失败')
        }
      } catch (err) {
        console.error('Error returning device:', err)
        this.$myMessageBox('归还设备失败，请稍后重试')
      }
    },
    formatDate(dateString) {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    getStatusClass(status) {
      const statusMap = {
        pending: 'status-pending',
        approved: 'status-approved',
        rejected: 'status-rejected',
        completed: 'status-completed',
        cancelled: 'status-cancelled'
      }
      return statusMap[status] || 'status-pending'
    },
    getStatusText(status) {
      const statusMap = {
        pending: '待审核',
        approved: '已批准',
        rejected: '已拒绝',
        completed: '已完成',
        cancelled: '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    showCommentForm(booking) {
      this.currentBooking = booking;
      this.showCommentDialog = true;
    },
    handleFeedbackSubmitted() {
      this.showCommentDialog = false;
      this.currentBooking = null;
      this.fetchBookings();
    }
  },
  mounted() {
    this.fetchBookings()
  }
}
</script>

<template>
  <div class="user-bookings">
    <div class="header">
      <h2>我的预约记录</h2>
      <div class="filter-section">
        <select v-model="selectedStatus" class="status-filter">
          <option value="all">全部预约</option>
          <option value="pending">待审核</option>
          <option value="approved">已批准</option>
          <option value="rejected">已拒绝</option>
          <option value="completed">已完成</option>
          <option value="cancelled">已取消</option>
          <option value="commented">已评价</option>
        </select>
      </div>
    </div>

    <div v-if="loading" class="loading">
      加载中...
    </div>

    <div v-else-if="filteredBookings.length === 0" class="no-bookings">
      暂无预约记录
    </div>

    <div v-else class="bookings-list">
      <div v-for="booking in filteredBookings" :key="booking.id" class="booking-card">
        <div class="booking-header">
          <h3>{{ booking.deviceTitle }}</h3>
          <span :class="['status-badge', getStatusClass(booking.status)]">
            {{ getStatusText(booking.status) }}
          </span>
        </div>
        
        <div class="booking-info">
          <p><strong>开始时间：</strong>{{ formatDate(booking.startTime) }}</p>
          <p><strong>结束时间：</strong>{{ formatDate(booking.endTime) }}</p>
          <p><strong>使用目的：</strong>{{ booking.purpose }}</p>
          <p v-if="booking.remark"><strong>备注：</strong>{{ booking.remark }}</p>
        </div>

        <div class="booking-actions">
          <button 
            v-if="booking.status === 'pending'"
            class="cancel-btn"
            @click="cancelBooking(booking.id)"
          >
            取消预约
          </button>
          <button 
            v-if="booking.status === 'approved'"
            class="return-btn"
            @click="returnDevice(booking.id)"
          >
            归还设备
          </button>
          <button 
            v-if="booking.status === 'completed' && !booking.hasComment"
            class="comment-btn"
            @click="showCommentForm(booking)"
          >
            评价设备
          </button>
          <span 
            v-if="booking.status === 'completed' && booking.hasComment"
            class="commented-badge"
          >
            已评价
          </span>
        </div>
      </div>
    </div>
  </div>

  <!-- 评价对话框 -->
  <div class="comment-dialog" v-if="showCommentDialog">
    <div class="dialog-content">
      <device-feedback-form
        v-if="currentBooking"
        :device-id="currentBooking.deviceId"
        @feedback-submitted="handleFeedbackSubmitted"
      />
    </div>
  </div>
</template>

<style scoped>
.user-bookings {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #eee;
}

.header h2 {
  margin: 0;
  color: #333;
}

.loading, .no-bookings {
  text-align: center;
  padding: 40px;
  color: #666;
}

.bookings-list {
  display: grid;
  gap: 20px;
}

.booking-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.booking-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.booking-header h3 {
  margin: 0;
  color: #333;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background: #fff3cd;
  color: #856404;
}

.status-approved {
  background: #d4edda;
  color: #155724;
}

.status-rejected {
  background: #f8d7da;
  color: #721c24;
}

.status-completed {
  background: #e2e3e5;
  color: #383d41;
}

.status-cancelled {
  background: #f8f9fa;
  color: #6c757d;
}

.booking-info {
  margin-bottom: 15px;
}

.booking-info p {
  margin: 8px 0;
  color: #666;
}

.booking-info strong {
  color: #333;
  margin-right: 8px;
}

.booking-actions {
  display: flex;
  justify-content: flex-end;
}

.cancel-btn {
  padding: 6px 12px;
  background: #dc3545;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.cancel-btn:hover {
  background: #c82333;
}

.return-btn {
  padding: 6px 12px;
  background: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
  margin-left: 10px;
}

.return-btn:hover {
  background: #218838;
}

.comment-btn {
  padding: 6px 12px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
  margin-left: 10px;
}

.comment-btn:hover {
  background: #0056b3;
}

.commented-badge {
  padding: 6px 12px;
  background: #e8f5e9;
  color: #2e7d32;
  border-radius: 4px;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.commented-badge::before {
  content: "✓";
  font-weight: bold;
}

.comment-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
}

.dialog-content h3 {
  margin: 0 0 20px;
  color: #2c3e50;
  text-align: center;
}

.rating-section {
  margin-bottom: 20px;
}

.rating-stars {
  display: inline-block;
  margin-left: 10px;
}

.star {
  font-size: 24px;
  color: #ddd;
  cursor: pointer;
  transition: color 0.3s;
}

.star.active {
  color: #ffd700;
}

.feedback-section {
  margin-bottom: 20px;
}

.feedback-section label {
  display: block;
  margin-bottom: 8px;
  color: #666;
}

textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
}

.dialog-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.dialog-buttons button {
  padding: 8px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-cancel {
  background: #f8f9fa;
  color: #666;
}

.btn-submit {
  background: #007bff;
  color: white;
}

.btn-submit:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.btn-cancel:hover {
  background: #e9ecef;
}

.btn-submit:hover:not(:disabled) {
  background: #0056b3;
}

.filter-section {
  margin-bottom: 20px;
}

.status-filter {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
  background-color: white;
  cursor: pointer;
  min-width: 120px;
}

.status-filter:hover {
  border-color: #007bff;
}

.status-filter:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
}
</style> 